﻿using Microsoft.AspNetCore.Cors;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Framework.AspNetCore.Extensons
{
	/// <summary>
	/// 跨域配置扩展类
	/// </summary>
	public static class CorsAccessorServiceCollectionExtensions
	{
		/// <summary>
		/// 配置跨域
		/// </summary>
		/// <param name="services">服务集合</param>
		/// <param name="DefaultCorsPolicyName"></param>
		/// <returns>服务集合</returns>
		public static IServiceCollection AddCorsAccessor(this IServiceCollection services, string DefaultCorsPolicyName)
		{
			var configuration = services.GetConfiguration();
			services.AddCors(_ =>
			{
				_.AddPolicy(DefaultCorsPolicyName, builder =>
				{
					builder
						.WithOrigins(
							configuration["App:CorsOrigins"]!
								.Split(";", StringSplitOptions.RemoveEmptyEntries)
								.Select(o => o.RemovePostFix("/"))
								.ToArray()
						)
						.WithAbpExposedHeaders()                                            // 增加 Abp 暴露的Header
						.WithExposedHeaders("access_token", "refresh_token")    // 增加token刷新时暴露的Header access_token和refresh_token
						.SetIsOriginAllowedToAllowWildcardSubdomains()                      // 可以匹配一个配置的带通配符的域名
						.AllowAnyHeader()                                                   // 允许任意头
						.AllowAnyMethod()                                                   // 允许任意方法
						.AllowCredentials();                                                // 允许cookie
				});
			});

			return services;
		}
	}
}
